from db_connect import ConnMysql
from db_connect import ConnRedis
from db_connect import ConnMysqlSlave
import aiomysql
import asyncio


class Methods():
    # 查询所有数据
    async def select_info(self, sql, args=None):
        async with ConnMysqlSlave().pool.acquire() as conn:
            async with conn.cursor(aiomysql.DictCursor) as cur:
                if args == None:
                    await cur.execute(sql)
                    result_info = await cur.fetchall()

                else:
                    await cur.execute(sql, args)
                    result_info = await cur.fetchall()
                    if result_info:
                        return result_info
                    else:
                        return result_info
    # 插入数据
    async def insert_info(self, sql, args=None):
        async with ConnMysql().pool.acquire() as p:
            async with p.cursor(aiomysql.DictCursor) as cur:
                if args == None:
                    await cur.execute(sql)
                    await p.commit()
                    return 'no args'
                else:
                    await cur.execute(sql, args)
                    await p.commit()
                    return 'ok'
    # 更新数据
    async def update_info(self, sql, args=None):
        #更改用户信息
        async with ConnMysql().pool.acquire() as p:
            async with p.cursor(aiomysql.DictCursor) as cur:
                if args == None:
                    await cur.execute(sql)
                    await p.commit()
                    return 'no args'
                else:
                    await cur.execute(sql, args)
                    await p.commit()
                    return 'ok'
    # 查询一组数据
    async def select_one(self, sql, args=None):
        # 传入sql，只取一组数据
        async with ConnMysqlSlave().pool.acquire() as p:
            async with p.cursor(aiomysql.DictCursor) as cur:
                # 无参数返回
                if args == None:
                    await cur.execute(sql)
                    result_info = await cur.fetchone()
                    return result_info
                # 有参数返回
                else:
                    await cur.execute(sql, args)
                    result_info = await cur.fetchone()
                    return result_info
    # 删除数据
    async def delect_info(self, sql, args):
        async with ConnMysql().pool.acquire() as p:
            async with p.cursor(aiomysql.DictCursor) as cur:
                if args == None:
                    await cur.execute(sql)
                    await p.commit()
                else:
                    await cur.execute(sql, args)
                    await p.commit()
                    return 'ok'